package com.gamerank.service.score.impl;

import java.math.BigInteger;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gamerank.bean.GameRankInfo;
import com.gamerank.service.base.DAOSupport;
import com.gamerank.service.score.GameRankService;

@Service
@Transactional
public class GameRankServiceImpl extends DAOSupport implements GameRankService {

	@Override
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public Integer getRanking(String gameName, String deviceID) {
		String entityName = this.getEntityName(GameRankInfo.class);
		String querySQL = "SELECT count(*) + 1 " + "FROM  "
				+ "( SELECT t1.gameScore FROM " + entityName
				+ " t1  WHERE t1.gameName = '" + gameName + "')  gs "
				+ "WHERE   " + "gs.gameScore  >  "
				+ "( SELECT t2.gameScore FROM " + entityName + " t2 "
				+ "WHERE t2.gameName = '" + gameName + "' and  t2.deviceId = '"
				+ deviceID + "' ) ";
		Query queryTR = em.createNativeQuery(querySQL);
		if(queryTR.getSingleResult() instanceof BigInteger){
			return ((BigInteger) queryTR.getSingleResult()).intValue();
		} 
		return (Integer) queryTR.getSingleResult();
	}
	
}
